package com.dk.util.http.req;

import com.dk.domain.ApiAutoTestEntity;
import com.dk.util.String.StringUtil;
import com.dk.util.config.ReadConfig;
import com.dk.util.http.OkHttpBuild;
import com.dk.util.json.JsonUtil;
import com.dk.util.log.Log;
import com.google.common.base.Strings;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * GET请求实现类
 */
public class GetHandler implements ReqStrategy{
    /**
     * GET请求实现类
     * @param apiAutoTestEntity 请求实体类
     * @return
     */
    @Override
    public Response request(ApiAutoTestEntity apiAutoTestEntity) {
        //请求对象
        Request req;
        //响应对象
        Response res = null;
        //拼接协议版本+域名或ip+路由
        String url = StringUtil.splicingProtocolAndUrl(apiAutoTestEntity.getProtocol(), apiAutoTestEntity.getUrl());
        //请求头
        String headers = apiAutoTestEntity.getHeaders();
        //创建url构建器
        HttpUrl.Builder uriBuilder = HttpUrl.parse(url).newBuilder();
        if(!Strings.isNullOrEmpty(headers)){
            //获取请求头String类型Map
            Map<String,String> headersHashMap = JsonUtil.parseJsonToHashMapForString(headers);
            //构造请求对象
            req = new Request
                    .Builder()//开始构建
                    .get()//使用get请求方式
                    .headers(Headers.of(headersHashMap))//添加消息头
                    .url(uriBuilder.build())//设置地址对象
                    .build();//完成构建
        }else{
            req = new Request
                    .Builder()//开始构建
                    .get()//使用get请求方式
                    .url(uriBuilder.build())//设置地址对象
                    .build();//完成构建
        }
        //获取通信对象
        Call call = OkHttpBuild.okHttpClient.newCall(req);
        try {
            //发送请求获取响应对象
            res = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
            Log.error("---【error】:发送GET请求io异常,用例编码:" + apiAutoTestEntity.getCaseNum() + ";");
        }
        return res;
    }

    public static void main(String[] args) {

    }
}
